"""
Django管理后台配置
定义了各个模型在管理后台的显示方式
"""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils import timezone

from .models import User, Category, Novel, Chapter, Bookshelf, AuthorApplication


# 自定义用户管理
class CustomUserAdmin(UserAdmin):
    """自定义用户管理界面"""
    list_display = ('username', 'email', 'role', 'date_joined', 'is_staff')
    list_filter = ('role', 'is_staff', 'is_active', 'date_joined')
    fieldsets = UserAdmin.fieldsets + (
        ('扩展信息', {'fields': ('role', 'avatar', 'bio')}),
    )
    search_fields = ('username', 'email')


# 小说章节内联显示
class ChapterInline(admin.TabularInline):
    """在小说详情页内联显示章节"""
    model = Chapter
    extra = 1  # 默认显示1个空的章节表单


# 小说管理
class NovelAdmin(admin.ModelAdmin):
    """小说管理界面"""
    list_display = ('title', 'author', 'category', 'status', 'created_at', 'updated_at')
    list_filter = ('status', 'category', 'created_at')
    search_fields = ('title', 'author__username', 'description')
    inlines = [ChapterInline]  # 内联显示章节


# 章节管理
class ChapterAdmin(admin.ModelAdmin):
    """章节管理界面"""
    list_display = ('title', 'novel', 'order', 'created_at', 'updated_at')
    list_filter = ('novel', 'created_at')
    search_fields = ('title', 'novel__title', 'content')


# 书架管理
class BookshelfAdmin(admin.ModelAdmin):
    """书架管理界面"""
    list_display = ('user', 'novel', 'last_read_chapter', 'added_at')
    list_filter = ('added_at',)
    search_fields = ('user__username', 'novel__title')


# 作者申请管理
class AuthorApplicationAdmin(admin.ModelAdmin):
    """作者申请管理界面"""
    list_display = ('user', 'status', 'created_at', 'processed_at')
    list_filter = ('status', 'created_at', 'processed_at')
    search_fields = ('user__username', 'reason', 'admin_notes')
    readonly_fields = ('created_at',)

    def save_model(self, request, obj, form, change):
        """保存模型时的处理"""
        # 如果状态从'pending'变为'approved'，则更新用户角色
        if 'status' in form.changed_data and obj.status == 'approved':
            if not obj.processed_at:
                obj.processed_at = timezone.now()
            user = obj.user
            user.role = 'author'
            user.save()
        super().save_model(request, obj, form, change)


# admin.py
class NovelAdmin(admin.ModelAdmin):
    list_filter = ('status', 'category')
    list_display = ('title', 'author', 'status')

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if not request.user.is_superuser:
            return qs.exclude(status='draft')
        return qs


# 注册模型
admin.site.register(User, CustomUserAdmin)
admin.site.register(Category)
admin.site.register(Novel, NovelAdmin)
admin.site.register(Chapter, ChapterAdmin)
admin.site.register(Bookshelf, BookshelfAdmin)
admin.site.register(AuthorApplication, AuthorApplicationAdmin)
